
// 1. 创建store对象 存储默认状态0
// 2. 将store对象放在一个全局的 组件可以够的到的地方
// 3. 让组件获取store对象中的状态 并将状态显示在组件中
import { observable, configure, action, runInAction, flow, computed, autorun } from 'mobx';
import axios from 'axios';

// 通过配置强制程序使用action函数更改应用程序中的状态
configure({ enforceActions: 'observed' });
const apples = [{
    "id": 0,
    "weight": 233,
    "isEaten": false
},
{
    "id": 1,
    "weight": 235,
    "isEaten": true
},
{
    "id": 2,
    "weight": 256,
    "isEaten": false
}];
class CounterStore {
    @observable curApples = 0;
    @observable eatenApples = 0;
    @observable items = [];

    @action.bound handleEatApple(apple) {
        this.items.forEach(item => {
            if (item.id === apple.id) item.isEaten = true;
        })
        this.updateData();
    }
    @action.bound handleGetAnApple() {
        let apple = {
            id: this.items.length + 1,
            weight: 230 + this.items.length + 1,
            isEaten: false
        }
        this.items.push(apple);
        this.updateData();
    }

    @action.bound handleGetApple() {
        this.items = apples;
        this.updateData();
    }

    updateData() {
        this.curApples = 0;
        this.eatenApples = 0;
        this.items.forEach(a => {
            a.isEaten ? this.eatenApples++ : this.curApples++;
        });
    }
}

const counter = new CounterStore();

export default counter;